package com.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.constant.MessageConstant;
import com.constant.RedisMessageConstant;
import com.pojo.Member;
import com.qiniu.util.Json;
import com.result.Result;
import com.service.MemberService;
import com.utils.DateUtils;
import com.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberMobileController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;


    @RequestMapping("/login")
    public Result login(@RequestBody Map loginInfo, HttpServletResponse response) throws Exception {
        String telephone = (String) loginInfo.get("telephone");

        Result valid = ValidateCodeUtils.isValid(jedisPool, loginInfo, RedisMessageConstant.SENDTYPE_LOGIN);
        if(!valid.isFlag()){//验证没通过
            return valid;
        }
        //验证通过了
        //1.通过手机号码判断是不是会员
        Member member = memberService.login(telephone);
            //登录、向客户端写入Cookie内容为用户手机号
            Cookie cookie=new Cookie("login_member_telephone", telephone);
            cookie.setMaxAge(60*60*24*3);
            cookie.setPath("/");
            response.addCookie(cookie);
            //将会员信息保存到redis，使用手机号作为key，保存时长为30分钟
            Jedis jedis = jedisPool.getResource();
            DateUtils.parseDate2String(member.getRegtime());
            jedis.setex(telephone,1800, JSON.toJSON(member).toString());
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }



}
